<?php

namespace plugin\ycMassage\app\admin\controller;

use app\common\builder\FormBuilder;
use app\common\builder\ListBuilder;
use app\common\service\UploadService;
use app\common\trait\SettingsTrait;
use FormBuilder\Factory\Elm;
use plugin\ycMassage\app\BaseController;
use plugin\ycMassage\app\model\MassageOrdersAddress;
use plugin\ycMassage\app\model\MassageRegions;
use plugin\ycMassage\app\model\MassageUser;
use plugin\ycMassage\app\model\MassageUserTechnician;
use plugin\ycMassage\app\model\MassageUserTechnicianQualifications;
use plugin\ycMassage\app\model\MassageUserTechnicianScheduling;
use plugin\ycMassage\app\model\MassageUserTechnicianThumb;
use plugin\ycMassage\app\validate\MassageTechnician;
use plugin\ycMassage\utils\enum\Examine;
use plugin\ycMassage\utils\enum\Gender;
use plugin\ycMassage\utils\enum\NoticeType;
use plugin\ycMassage\utils\enum\State;
use plugin\ycMassage\utils\notice\Notice;
use support\Request;
use think\facade\Db;

class TechnicianController extends BaseController
{
    use SettingsTrait;

    /**
     * 应用ID（null则获取系统配置）
     * @var int|null
     * @author 贵州猿创科技有限公司
     * @email 416716328@qq.com
     */
    protected $saas_appid = null;

    /**
     * 构造函数
     * @return void
     * @author 贵州猿创科技有限公司
     * @copyright 贵州猿创科技有限公司
     * @email 416716328@qq.com
     */
    public function initialize()
    {
        parent::initialize();
        $this->saas_appid = $this->request->saas_appid;
    }
    public function indexGetTable(Request $request)
    {
        $limit   = $request->get('limit', 20);
        $builder = new ListBuilder;
        $builder->addActionOptions('操作', [
            'width' => 250
        ]);
        $builder->pageConfig([
            'pageSize' => $limit
        ]);
        $builder->addScreen('name', 'input', '技师搜索', [
            'placeholder' => '姓名、手机号搜索'
        ]);
        $builder->addScreen('examine', 'select', '审核状态', [
            'options' => Examine::getOptions()
        ]);

        $builder->addTopButton('add', '添加技师', [
            'api'       => $this->pluginPrefix . '/admin/Technician/create',
            'path' => '/Technician/create',
            'type'      => 'modal'
        ], [
            'title' => '创建用户',
        ], [
            'type' => 'success'
        ]);
        $builder->addRightButton('examine', '审核', [
            'api'    => $this->pluginPrefix . '/admin/Technician/examine',
            'path' => '/Technician/examine',
            'type'      => 'modal',
            'aliasParams' => [
                'uid' => 'id'
            ],
            'params' => [
                'field' => 'examine',
                'where' => '=',
                'value' => 0
            ]
        ], [], [
            'type' => 'danger',
            'link' => true
        ]);
        $builder->addRightButton('edit', '修改', [
            'api'    => $this->pluginPrefix . '/admin/Technician/update',
            'path' => '/Technician/update',
            'type'      => 'modal',
            'aliasParams' => [
                'uid' => 'id'
            ],
        ], [], [
            'type' => 'primary',
            'link' => true
        ]);
        $builder->addRightButton('thumb', '照片', [
            'api'    => $this->pluginPrefix . '/admin/TechnicianThumb/index',
            'path' => '/TechnicianThumb/index',
            'aliasParams' => [
                'uid'
            ],
        ], [], [
            'type' => 'success',
            'link' => true
        ]);
        $builder->addRightButton('scheduling', '排班', [
            'api'    => $this->pluginPrefix . '/admin/Technician/scheduling',
            'path' => '/Technician/scheduling',
            'aliasParams' => [
                'uid' => 'id'
            ],
            'params' => [
                'field' => 'is_mch',
                'where' => '=',
                'value' => 0
            ]
        ], [
            'title' => '技师排班',
        ], [
            'type' => 'danger',
            'link' => true
        ]);
        $builder->addRightButton('schedulingSituation', '排班情况', [
            'api'    => $this->pluginPrefix . '/admin/Technician/schedulingSituation',
            'path' => '/Technician/schedulingSituation',
            'aliasParams' => [
                'uid' => 'id'
            ]
        ], [
            'title' => '排班情况',
        ], [
            'type' => 'success',
            'link' => true
        ]);
        $builder->rowConfig([
            'keyField' => 'uid'
        ]);
        $builder->addColumn('uid', 'UID', [
            'width' => 90
        ])
            ->addColumnEle('headimg', '头像', [
                'width' => 60,
                'params' => [
                    'type' => 'image',
                ],
            ])
            ->addColumn('nickname', '昵称', [
                'width' => 120,
            ])
            ->addColumnEle('is_mch', '身份', [
                'width' => 100,
                'params' => [
                    'type' => 'tags',
                    'options' => [
                        0 => '个人',
                        1 => '商户技师'
                    ],
                    'style' => [
                        0 => [
                            'type' => ''
                        ],
                        1 => [
                            'type' => 'success'
                        ]
                    ]
                ],
            ])
            ->addColumn('realname', '姓名', [
                'width' => 120,
            ])
            ->addColumn('mobile', '联系电话', [
                'width' => 120,
            ])
            ->addColumn('age', '年龄', [
                'width' => 80,
            ])
            ->addColumn('province', '省', [
                'width' => 120,
            ])
            ->addColumn('city', '市', [
                'width' => 120,
            ])
            ->addColumn('gender_text', '性别', [
                'width' => 80,
            ])
            ->addColumn('work_meet', '工龄', [
                'width' => 80,
            ])
            ->addColumn('recommend', '推荐结束时间', [
                'width' => 160,
            ])
            ->addColumn('appointment_time', '可预约时间', [
                'width' => 160,
            ])
            ->addColumnEle('resting', '状态', [
                'width' => 100,
                'params' => [
                    'type' => 'switch',
                    'api' => $this->pluginPrefix . '/admin/Technician/updateState',
                    'checked' => [
                        'value' => State::NO['value'],
                        'text' => '接单中',
                    ],
                    'unchecked' => [
                        'value' => State::YES['value'],
                        'text' => '休息中',
                    ]
                ],
            ])
            ->addColumnEle('examine', '审核状态', [
                'width' => 100,
                'params' => [
                    'type' => 'tags',
                    'options' => Examine::dictOptions(),
                    'style' => Examine::dictOptions('style')
                ],
            ])
            ->addColumn('message', '审核结果', [
                'minWidth' => 120,
            ]);
        return $this->successRes($builder->create());
    }
    public function index(Request $request)
    {
        $page = $request->get('page', 1);
        $limit = $request->get('limit', 20);
        $where = [
            ['t.saas_appid', '=', $request->saas_appid]
        ];
        $name = $request->get('name');
        if ($name) {
            $where[] = ['u.nickname|u.realname|t.mobile|u.mobile', 'like', "%{$name}%"];
        }
        $examine = $request->get('examine');
        if ($examine !== null) {
            $where[] = ['t.examine', '=', $examine];
        }
        $orders_id=$request->get('orders_id');
        $order='t.create_time desc';
        $field=[
            't.*',
            'u.headimg,u.nickname,u.realname'
        ];
        if($orders_id){
            $OrdersAddress=MassageOrdersAddress::where(['orders_id'=>$orders_id])->find();
            if ($OrdersAddress&&$OrdersAddress->longitude && $OrdersAddress->latitude) {
                $longitude = $OrdersAddress->longitude;
                $latitude = $OrdersAddress->latitude;
                $order = "distance IS NULL,distance asc,t.comment_grade desc,t.create_time desc";
                $field[] = "ROUND(6378.138 * 2 * ASIN(SQRT(POW(SIN(({$latitude} * PI() / 180 - t.latitude * PI() / 180) / 2),2) + COS({$latitude} * PI() / 180) * COS(t.latitude * PI() / 180) * POW(SIN(({$longitude} * PI() / 180 - t.longitude * PI() / 180) / 2),2))) * 1000) AS distance";
            }
        }
        $startDay = strtotime(date('Y-m-d') . ' 00:00:00');
        $endTime = time();
        $data = MassageUserTechnician::where($where)
            ->alias('t')
            ->join('massage_user u', 'u.id = t.uid')
            ->orderRaw($order)
            ->fieldRaw(implode(',', $field))
            ->paginate([
                'list_rows' => $limit,
                'page' => $page
            ])->each(function ($item)use($startDay,$endTime) {
                $item->nickname = base64_decode($item->nickname);
                if (strpos($item->headimg, 'http') !== 0) {
                    $item->headimg = UploadService::url($item->headimg);
                }
                $item->is_mch = 0;
                if ($item->work_mch_id) {
                    $item->is_mch = 1;
                }
                if ($item->recommend && $item->recommend < date('Y-m-d H:i:s')) {
                    $item->recommend = '已结束';
                }
                $item->distance_text = null;
                if ($item->distance !== null) {
                    if ($item->distance > 1000) {
                        $item->distance_text = round($item->distance / 1000, 2) . 'km';
                    } else {
                        $item->distance_text = round($item->distance) . 'm';
                    }
                }
                # 计算排期
                $item->appointment = State::YES['value'];
                # 查询已开始的排期
                if(!$item->resting){
                    $Scheduling = MassageUserTechnicianScheduling::where(['uid' => $item->uid, 'saas_appid' => $item->saas_appid])
                        ->whereBetweenTimeField('start_time', 'end_time')
                        ->whereRaw('(`appointment_time` IS NULL OR `appointment_time`<`end_time`)')
                        ->find();
                    if ($Scheduling) {
                        if ($Scheduling->appointment_time) {
                            $item->appointment_time = MassageGetAppointmentTime($Scheduling->appointment_time);
                        } else {
                            $item->appointment_time = '随时可约';
                        }
                    }
                    if (!$item->appointment_time) {
                        # 查询未开始的排期
                        $Scheduling = MassageUserTechnicianScheduling::where(['uid' => $item->uid, 'saas_appid' => $item->saas_appid])
                            ->whereTime('start_time', '>=', $startDay)
                            ->whereTime('end_time', '>=', $endTime)
                            ->whereRaw("(`appointment_time` IS NULL OR `appointment_time` < `end_time`)")
                            ->find();
                        if ($Scheduling) {
                            if ($Scheduling->appointment_time) {
                                $item->appointment_time = MassageGetAppointmentTime($Scheduling->appointment_time);
                            } else {
                                $item->appointment_time = MassageGetAppointmentTime($Scheduling->start_time);
                            }
                        }
                    }
                }
                if (!$item->appointment_time) {
                    $item->appointment_time = '休息中';
                    $item->appointment = State::NO['value'];
                }
            });
        return $this->successRes($data);
    }
    public function create(Request $request)
    {
        $saas_appid = $request->saas_appid;
        if ($request->method() === 'POST') {
            $D = $request->post();
            hpValidate(MassageTechnician::class, $D, 'admin_create');
            Db::startTrans();
            try {
                $mobile = $D['mobile'];
                $userModel = MassageUser::where(['mobile' => $mobile, 'saas_appid' => $saas_appid])->find();
                if ($userModel && MassageUserTechnician::where(['uid' => $userModel->id])->count()) {
                    throw new \Exception('手机号已入驻技师');
                }
                if (!$userModel) {
                    $userModel = new MassageUser;
                    $userModel->saas_appid = $saas_appid;
                    $userModel->mobile = $mobile;
                    $userModel->nickname = $D['nickname'];
                    $userModel->headimg = UploadService::path($D['thumb'][0]);
                    $userModel->save();
                }
                $MassageUserTechnician = new MassageUserTechnician;
                $MassageUserTechnician->uid = $userModel->id;
                $MassageUserTechnician->saas_appid = $saas_appid;
                if (!empty($D['mch_id'])) {
                    $MassageUserTechnician->mch_id = (int)$D['mch_id'];
                }
                $MassageUserTechnician->age = (int)$D['age'];
                list($province_id, $city_id) = $D['regions'];
                $MassageUserTechnician->province_id = (int)$province_id;
                $MassageUserTechnician->province = MassageRegions::where(['id' => $province_id])->value('title');
                $MassageUserTechnician->city_id = $city_id;
                $MassageUserTechnician->city = MassageRegions::where(['id' => $city_id])->value('title');
                $MassageUserTechnician->gender = $D['gender'];
                $MassageUserTechnician->mobile = $D['mobile'];
                $MassageUserTechnician->work_meet = $D['work_meet'];
                $MassageUserTechnician->examine = $D['examine'];
                $MassageUserTechnician->virtually_order_num = $D['virtually_order_num'];
                if (!empty($D['recommend'])) {
                    $MassageUserTechnician->recommend = $D['recommend'];
                }
                $MassageUserTechnician->save();
                $MassageUserTechnicianThumb = new MassageUserTechnicianThumb;
                $thumb = [];
                foreach ($D['thumb'] as $key => $value) {
                    $temp = [
                        'uid' => $MassageUserTechnician->uid,
                        'saas_appid' => $saas_appid,
                        'url' => $value,
                    ];
                    krsort($temp);
                    $thumb[] = $temp;
                }
                $MassageUserTechnicianThumb->saveAll($thumb);
                Db::commit();
                return $this->success('添加成功');
            } catch (\Throwable $th) {
                Db::rollback();
                return $this->fail($th->getMessage());
            }
        }

        $builder = new FormBuilder;
        $builder->setMethod('POST');
        $builder->addComponent('nickname', 'input', '昵称', '', [
            'col' => 12,
        ]);
        $this->getFormBuilder($builder, $saas_appid);
        $builder->addComponent('thumb', 'uploadify', '技师图片', '', [
            'col' => 24,
            'props' => [
                'type' => 'image',
                'limit' => 9,
                'format' => ['jpg', 'jpeg', 'png']
            ],
        ]);
        $data = $builder->create();
        return $this->successRes($data);
    }
    public function update(Request $request)
    {
        $id = $request->get('id');
        $saas_appid = $request->saas_appid;
        $MassageUserTechnician = MassageUserTechnician::where(['uid' => $id, 'saas_appid' => $request->saas_appid])->find();
        if (!$MassageUserTechnician) {
            return $this->fail('数据不存在');
        }
        if ($request->method() === 'POST') {
            $D = $request->post();
            hpValidate(MassageTechnician::class, $D, 'admin_update');
            Db::startTrans();
            try {
                $MassageUserTechnician->age = (int)$D['age'];
                list($province_id, $city_id) = $D['regions'];
                $MassageUserTechnician->province_id = (int)$province_id;
                $MassageUserTechnician->province = MassageRegions::where(['id' => $province_id])->value('title');
                $MassageUserTechnician->city_id = $city_id;
                $MassageUserTechnician->city = MassageRegions::where(['id' => $city_id])->value('title');
                $MassageUserTechnician->gender = $D['gender'];
                $MassageUserTechnician->mobile = $D['mobile'];
                $MassageUserTechnician->work_meet = $D['work_meet'];
                $MassageUserTechnician->examine = $D['examine'];
                $MassageUserTechnician->virtually_order_num = $D['virtually_order_num'];
                if (!empty($D['recommend'])) {
                    $MassageUserTechnician->recommend = $D['recommend'];
                } else {
                    $MassageUserTechnician->recommend = null;
                }
                $MassageUserTechnician->save();
                Db::commit();
                return $this->success('保存成功');
            } catch (\Throwable $th) {
                Db::rollback();
                return $this->fail($th->getMessage());
            }
        }

        $builder = new FormBuilder;
        $builder->setMethod('POST');
        $this->getFormBuilder($builder, $saas_appid);
        $MassageUserTechnician->regions = [
            $MassageUserTechnician->province_id,
            $MassageUserTechnician->city_id
        ];
        $data = $builder->setData($MassageUserTechnician)->create();
        return $this->successRes($data);
    }
    public function getFormBuilder($builder, $saas_appid)
    {
        $builder->addRow('gender', 'radio', '性别', '', [
            'col' => 12,
            'options' => Gender::getOptions(),
        ]);
        $builder->addRow('mobile', 'input', '手机号', '', [
            'col' => 12,
            'prompt' => [
                'text' => "手机号将作为用户登录账号，请务必认真填写",
            ],
        ]);
        $builder->addRow('age', 'number', '年龄', null, [
            'col' => 12,
            'props' => [
                'controls' => false
            ]
        ]);
        $builder->addRow('work_meet', 'number', '工龄', null, [
            'col' => 12,
            'props' => [
                'controls' => false
            ]
        ]);
        $regions = MassageRegions::getCache($saas_appid);
        $regionsData = [];
        foreach ($regions as $key => $province) {
            $temp = [
                'id' => $province['id'],
                'title' => $province['title'],
                'children' => []
            ];
            foreach ($province['children'] as $key => $city) {
                $temp['children'][] = [
                    'id' => $city['id'],
                    'title' => $city['title'],
                    'children' => []
                ];
            }
            $regionsData[] = $temp;
        }
        $builder->addRow('regions', 'city', '地区', [], [
            'col' => 12,
            'options' => $regionsData,
            'props' => [
                'filterable' => true,
                'placeholder' => '请选择地区',
                'clearable' => true,
                'props' => [
                    'value' => 'id',
                    'label' => 'title',
                    'children' => 'children'
                ]
            ]
        ]);
        $builder->addRow('examine', 'radio', '状态', Examine::WAIT['value'], [
            'col' => 12,
            'options' => Examine::getOptions(),
        ]);
        $builder->addRow('recommend', 'dateTime', '推荐(可选)', '', [
            'col' => 12,
            'props' => [
                'type' => 'datetime',
                'format' => 'YYYY-MM-DD HH:mm:ss',
                'value-format' => 'YYYY-MM-DD HH:mm:ss',
                'clearable' => true,
                'placeholder' => '请选择时间',
            ]
        ]);
        $builder->addRow('order_num', 'number', '订单量', null, [
            'col'           => 6,
            'props' => [
                'precision' => 0,
                'controls' => false,
                'min' => 0,
                'disabled' => true
            ]
        ]);
        $builder->addRow('virtually_order_num', 'number', '虚拟订单量', null, [
            'col'           => 6,
            'props' => [
                'precision' => 0,
                'controls' => false,
                'min' => 0
            ]
        ]);
    }
    public function examine(Request $request)
    {
        $id = $request->get('id');
        $MassageUserTechnician = MassageUserTechnician::where(['uid' => $id, 'saas_appid' => $request->saas_appid, 'examine' => Examine::WAIT['value']])->find();
        if (!$MassageUserTechnician) {
            return $this->fail('数据不存在');
        }
        if ($request->method() === 'POST') {
            $D = $request->post();
            $MassageUserTechnician->examine = $D['examine'];
            Db::startTrans();
            try {
                if (!in_array($MassageUserTechnician->examine, [Examine::YES['value'], Examine::NO['value']])) {
                    throw new \Exception('请选择审核状态');
                }
                $notice = new Notice();
                $MassageUser = MassageUser::alias('u')->where(['u.id' => $MassageUserTechnician->uid])
                    ->join('MassageUserWechat uw', 'uw.uid=u.id', 'left')
                    ->field('u.nickname,u.mobile,uw.openid')
                    ->find();
                if ($MassageUser) {
                    $notice->addTECHNICIAN($MassageUser->mobile, $MassageUser->openid);
                }
                $notice->saas_appid = $MassageUserTechnician->saas_appid;
                $notice->type = NoticeType::EXAMINE['value'];
                $notice->role = ['TECHNICIAN'];
                if ($MassageUserTechnician->examine == Examine::NO['value']) {
                    if (empty($D['message'])) {
                        throw new \Exception('请填写驳回理由');
                    }
                    $notice->setData([
                        'type' => '技师入驻申请',
                        'state' => '已驳回',
                        'result' => $D['message'],
                        'trade' => $MassageUserTechnician->uid,
                        'time' => date('Y-m-d H:i:s')
                    ]);
                    $MassageUserTechnician->message = $D['message'];
                } else {
                    $notice->setData([
                        'type' => '技师入驻申请',
                        'state' => '已通过',
                        'result' => '恭喜您，您的入驻申请已通过',
                        'trade' => $MassageUserTechnician->uid,
                        'time' => date('Y-m-d H:i:s')
                    ]);
                    $MassageUserTechnician->message = '通过';
                }
                $MassageUserTechnician->save();
                if ($D['thumb_examine'] == Examine::YES['value']) {
                    $thumb = MassageUserTechnicianThumb::where(['uid' => $MassageUserTechnician->uid, 'saas_appid' => $MassageUserTechnician->saas_appid])->select();
                    foreach ($thumb as $key => $itme) {
                        $itme->examine = Examine::YES['value'];
                        $itme->save();
                    }
                }
                $notice->send();
                Db::commit();
                return $this->success('审核成功');
            } catch (\Throwable $th) {
                Db::rollback();
                return $this->fail($th->getMessage());
            }
        }

        $builder = new FormBuilder;
        $builder->setMethod('POST');

        $builder->addComponent('uid', 'info', 'UID', '', [
            'col'           => 6,
        ]);
        $builder->addComponent('name', 'info', '姓名', '', [
            'col'           => 6,
        ]);
        $builder->addComponent('mobile', 'info', '手机号', '', [
            'col'           => 6,
        ]);
        $builder->addComponent('age', 'info', '年龄', '', [
            'col'           => 6,
        ]);
        $builder->addComponent('province', 'info', '省', '', [
            'col'           => 6,
        ]);
        $builder->addComponent('city', 'info', '市', '', [
            'col'           => 6,
        ]);
        $builder->addComponent('gender_text', 'info', '性别', '', [
            'col'           => 6,
        ]);
        $builder->addComponent('work_meet', 'info', '工龄', '', [
            'col'           => 6,
        ]);
        $builder->addDivider('技师图片');
        $builder->addRow('thumb_examine', 'radio', '技师图片状态', 0, [
            'col' => 24,
            'options' => Examine::getOptions()
        ]);
        $thumb = MassageUserTechnicianThumb::where(['uid' => $MassageUserTechnician->uid, 'saas_appid' => $MassageUserTechnician->saas_appid])->field('url')->select();
        foreach ($thumb as $key => $itme) {
            $builder->addComponent('thumb_' . $key, 'el-image', '', '', [
                'col'           => 4,
                'props'         => [
                    'src'       => $itme->url,
                    'width'     => 160,
                    'height'    => 220
                ]
            ]);
        }
        $qualifications = MassageUserTechnicianQualifications::where(['uid' => $MassageUserTechnician->uid, 'saas_appid' => $MassageUserTechnician->saas_appid])->field('url')->select();
        if (!$qualifications->isEmpty()) {
            $builder->addDivider('从业资格证');
            foreach ($qualifications as $key => $itme) {
                $builder->addComponent('qualifications_' . $key, 'el-image', '', '', [
                    'col'           => 4,
                    'props'         => [
                        'src'       => $itme->url,
                        'width'     => 160,
                        'height'    => 220
                    ]
                ]);
            }
        }
        $builder->addDivider('审核');
        $builder->addRow('examine', 'radio', '状态', Examine::YES['value'], [
            'col' => 24,
            'options' => Examine::getOptions(),
            'control' => [
                [
                    'value' => Examine::NO['value'],
                    'where' => '==',
                    'rule' => [
                        Elm::textarea('message', '驳回理由')
                            ->col([
                                'span' => 24
                            ])
                            ->props([
                                'filterable' => true,
                                'placeholder' => '请输入驳回理由',
                            ])
                    ],
                ],
            ]
        ]);
        $data = $builder->setData($MassageUserTechnician)->create();
        return $this->successRes($data);
    }
    public function updateState(Request $request)
    {
        $value=$request->post('value');
        $uid=$request->post('uid');
        $field=$request->post('field');
        $MassageUserTechnician = MassageUserTechnician::where(['uid' => $uid, 'saas_appid' => $request->saas_appid])->find();
        if (!$MassageUserTechnician) {
            return $this->fail('数据不存在');
        }
        $MassageUserTechnician->$field = $value;
        if($MassageUserTechnician->save()){
            return $this->success('修改成功');
        }
        return $this->fail('修改失败');
    }
}
